<?php

namespace app;

class ErrorResult
{
    protected static $code = [
        // Members
        2002 => 'wrong account or password',

        9000 => 'JsonWebToken Expired',
        9001 => 'sign validation error'
    ];

    /**
     * 根据错误代码获取错误信息
     * @param int $_code 错误代码
     * @return string|bool 错误信息或布尔值
     */
    public static function Code2Msg(int $_code)
    {
        foreach (self::$code as $code => $value) {
            if ($code === $_code) {
                return $value;
            }
        }
        return false;
    }

    /**
     * 根据错误信息获取错误信代码
     * @param string $_msg 错误信息
     * @return int|bool 错误代码或布尔值
     */
    public static function Msg2Code(string $_msg)
    {
        foreach (self::$code as $code => $value) {
            if ($value === $_msg) {
                return (int)$code;
            }
        }
        return false;
    }

    /**
     * 根据ErrorCode返回错误信息,建议提供错误代码速度会较快
     * @param int|string $code 错误代码或错误信息
     * @param int $status 状态码
     * @param mixed $data 附加数据
     * @return \think\response
     */
    public static function ErrorResult($code, $status = 200, $data = [])
    {
        if (is_int($code)) {
            return response(['code' => $code, 'msg' => lang(self::$code[$code]), 'data' => $data, 'time' => time()], $status, [], 'json');
        } else {
            return response(['code' => self::Msg2Code($code), 'msg' => lang($code), 'data' => $data, 'time' => time()], $status, [], 'json');
        }
    }
}
